import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:iap_pay/iap_pay.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  List<String> _productLists = ['1000011', '1000022', '1000033', '1000055'];

  /// 下单Id
  int orderId = 0;

  int count = 5;
  int time = 0;

  /// 苹果后台商品Id
  String productId = '1000011';

  /// 未购买商品
  List<IAPItem> items = [];

  /// 已购买商品
  List<PurchasedItem> purchases = [];

  /// 待处理商品
  List<PurchasedItem> unhandles = [];

  /// 购买状态更新订阅
  StreamSubscription _purchaseUpdatedSubscription;

  /// 购买报错更新订阅
  StreamSubscription _purchaseErrorSubscription;

  @override
  void initState() {
    super.initState();
    initPlatformState();
    this.config();
  }

  void config() async {
    // prepare 查看是否能进行内支付
    var result = await IapPay.instance.check;
    print('CanInAppPurchase============: $result');
    _purchaseUpdatedSubscription =
        IapPay.purchaseUpdated.listen((PurchasedItem productItem) async {
      // 支付成功能来:Toast 无效
          debugPrint('购买成功');
          print('purchase-updated: $productItem');
          print('productItem${productItem.toString()}');
//      IapPay.showLoading('支付成功了');
//        Map<String, String> receiptBody = {
//          'receipt-data': productItem.transactionReceipt,
//          'password': '722a7552597e40cda39e5e983899052d'
//        };
//
//        ///finishTransactionIOS验证购买
//        var validateReceipt = await IapPay.instance.validateReceipt(
//          receiptBody: receiptBody,
//          isTest: AppConfig.isIosPayEnabled ? true : false,
//        );
//        print('validateReceipt========${validateReceipt}');
      //TODO:IAP第四步: 发送给服务端验证数据有效性
      //print('发送给服务端验证数发送给服务端验证数据有效性$据有效性${this.orderId}');

//          this.saveReceipt(
//            transactionReceipt: productItem.transactionReceipt,
//          );

//          this.notiServer(
//            transactionReceipt: productItem.transactionReceipt,
//            complete: () {
//              this.count = 0;
//              this.time = 0;
//              this.removeReceipt();
//            },
//          );
    });

    _purchaseErrorSubscription =
        IapPay.purchaseError.listen((PurchaseResult purchaseError) {
      //TODO:IAP第五步:错误日志上报
      String mesage;
      print('purchaseError${purchaseError.toJson()}');
      int code = purchaseError.responseCode;
      if (code == 0) {
        mesage = 'App Store 验证成功';
      } else if (code == 21000) {
        mesage = 'App Store不能读取你提供的JSON对象';
      } else if (code == 21002) {
        mesage = 'receipt-data属性中的数据格式错误或丢失';
      } else if (code == 21003) {
        mesage = 'receipt无法通过验证';
      } else if (code == 21004) {
        mesage = '提供的共享密码与帐户的文件共享密码不匹配';
      } else if (code == 21005) {
        mesage = 'receipt服务器当前不可用';
      } else if (code == 21006) {
        mesage =
            '该收据有效，但订阅已过期，当此状态代码返回到您的服务器时，收据数据也会被解码并作为响应的一部分返回，仅针对自动续订的iOS样式交易收据返回';
      } else if (code == 21007) {
        mesage = 'receipt是Sandbox receipt，但却发送至生产系统的验证服务';
      } else if (code == 21008) {
        mesage = 'receipt是生产receipt，但却发送至Sandbox环境的验证服务';
      } else if (code == 21010) {
        mesage = '此收据无法授权，就像从未进行过购买一样对待';
      } else {
        mesage = purchaseError.debugMessage ?? '未知错误';
      }
      IapPay.showLoading(mesage);
    });
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await IapPay.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = 360;
    double buttonWidth = (screenWidth / 3) - 20;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example for iap_pay'),
        ),
        body: Container(
          padding: EdgeInsets.all(10.0),
          child: ListView(
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    child: Text(
                      'Running on: $_platformVersion\n',
                      style: TextStyle(fontSize: 18.0),
                    ),
                  ),
                  Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          // config Step 1
                          Container(
                            width: buttonWidth,
                            height: 60.0,
                            margin: EdgeInsets.all(7.0),
                            child: FlatButton(
                              color: Colors.red,
                              padding: EdgeInsets.all(0.0),
                              onPressed: () async {
                                print(
                                    "---------- Connect Billing Button Pressed");
                                config();
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 20.0),
                                alignment: Alignment(0.0, 0.0),
                                child: Text(
                                  'Config-Step1',
                                  style: TextStyle(
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          // getProduct Step 2
                          Container(
                            width: buttonWidth,
                            height: 60.0,
                            margin: EdgeInsets.all(7.0),
                            child: FlatButton(
                              color: Colors.yellow,
                              padding: EdgeInsets.all(0.0),
                              onPressed: () async {
                                print(
                                    "---------- End Connection Button Pressed");

                                List<IAPItem> tempArray = await IapPay.instance
                                    .getProducts(_productLists);
                                for (var item in tempArray) {
                                  //print('getProduct==============>${item.toString()}');
                                  this.items.add(item);
                                }
                                setState(() {
                                  IapPay.showLoading(
                                      '商品总数:${this.items.length}');
                                });
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 20.0),
                                alignment: Alignment(0.0, 0.0),
                                child: Text(
                                  'getItem Step2',
                                  style: TextStyle(
                                    fontSize: 16.0,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            Container(
                                width: buttonWidth,
                                height: 60.0,
                                margin: EdgeInsets.all(7.0),
                                child: FlatButton(
                                  color: Colors.green,
                                  padding: EdgeInsets.all(0.0),
                                  onPressed: () async {
                                    print(
                                        "---------- Get Items Button Pressed");

                                    await IapPay.instance.endConnection;
                                    if (_purchaseUpdatedSubscription != null) {
                                      _purchaseUpdatedSubscription.cancel();
                                      _purchaseUpdatedSubscription = null;
                                    }
                                    if (_purchaseErrorSubscription != null) {
                                      _purchaseErrorSubscription.cancel();
                                      _purchaseErrorSubscription = null;
                                    }
                                  },
                                  child: Container(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 20.0),
                                    alignment: Alignment(0.0, 0.0),
                                    child: Text(
                                      'End',
                                      style: TextStyle(
                                        fontSize: 16.0,
                                      ),
                                    ),
                                  ),
                                )),

                          ]),
                    ],
                  ),
                  Column(
                    children: this._renderInApps(),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> _renderInApps() {
    List<Widget> widgets = this
        .items
        .map((item) => Container(
              margin: EdgeInsets.symmetric(vertical: 10.0),
              child: Container(
                child: Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(bottom: 5.0),
                      child: Text(
                        item.toString(),
                        style: TextStyle(
                          fontSize: 18.0,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    FlatButton(
                      color: Colors.orange,
                      onPressed: () {
                        print("---------- Buy Item Button Pressed");
                        this.requestPurchase(item);
                      },
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Container(
                              height: 48.0,
                              alignment: Alignment(-1.0, 0.0),
                              child: Text('Buy Item'),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ))
        .toList();
    return widgets;
  }

  void requestPurchase(IAPItem item) {
    IapPay.instance.requestPurchase(item.productId);
  }
}
